package com.poetize.plus.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.poetize.plus.entity.dto.WebInfoDTO;
import com.poetize.plus.entity.po.User;
import com.poetize.plus.entity.po.WebInfo;
import com.poetize.plus.entity.vo.HomeWebInfoVO;
import com.poetize.plus.entity.vo.StatisticsVO;
import com.poetize.plus.entity.vo.WebInfoVO;
import com.poetize.plus.mapper.ArticleMapper;
import com.poetize.plus.mapper.SortMapper;
import com.poetize.plus.mapper.UserMapper;
import com.poetize.plus.mapper.WebInfoMapper;
import com.poetize.plus.service.WebInfoService;
import com.poetize.plus.utils.BaseConstant;
import com.poetize.plus.utils.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @Author zuosy
 * @Date 2024/3/30 8:40
 **/
@Service
@RequiredArgsConstructor
public class WebInfoServiceImpl extends ServiceImpl<WebInfoMapper, WebInfo> implements WebInfoService {

    private final UserMapper userMapper;

    private final ArticleMapper articleMapper;

    private final SortMapper sortMapper;

    private final RedisUtil redisUtil;

    @Override
    public WebInfoVO queryWebInfo() {
        WebInfo webInfo = lambdaQuery().one();
        return Optional.ofNullable(webInfo)
                .map(WebInfoVO::convert)
                .orElseThrow(() -> new IllegalArgumentException(""));
    }

    @Override
    public Boolean updateWebInfo(WebInfoDTO webInfoDTO) {
        WebInfo webInfo = WebInfoDTO.convertDTO(webInfoDTO);
        boolean update = baseMapper.updateById(webInfo) > 0;
        if (!update){
            throw new IllegalArgumentException("数据异常");
        }
        redisUtil.setHomeRedis(BaseConstant.Redis.HOME_WEB_INFO, this::queryWebInfo);
        return true;
    }

    @Override
    public HomeWebInfoVO getWebInfo() {
        WebInfoVO webInfoVO = queryWebInfo();
        //头像
        User user = userMapper.selectById(-200L);
        return new HomeWebInfoVO(user.getAvatar(), webInfoVO.webName(), webInfoVO.webTitle(), webInfoVO.footer(), webInfoVO.waifuJson());
    }

    @Override
    public StatisticsVO getStatistics() {
        //文章数量
        var articleCount = articleMapper.selectCount(null);
        //分类数量
        var sortCount = sortMapper.selectCount(null);
        //热度
        var viewCount = articleMapper.sumViewCount();
        return new StatisticsVO( articleCount, sortCount, viewCount);
    }
}
